<!DOCTYPE html>

<script src="/js-test-resources/js-test.js"></script>
<script src="post-blob-content-type-tests.js"></script>
<script type="text/javascript">
  description("Test verifies that content MIME type is set correctly " +
              "when Blob is sent using " +
              "<a href='http://www.w3.org/TR/XMLHttpRequest/#the-send-method'>XMLHttpRequest asynchronously.</a>");

  var xhr;
  var expectedMimeType;
  window.jsTestIsAsync = true;
  var asyncTestCase = 0;

  function runNextAsyncTest() {
      asyncTestCase++;
      runAsyncTests();
  }

  function reportResult(e) {
      var testCase = xhrBlobTestCases[asyncTestCase];
      if (xhr.status === 200) {
          postedMimeType = JSON.parse(xhr.response)['content-type'];
          if (testCase.expectedMime === '') {
              shouldBeTrue("postedMimeType === undefined");
          } else {
              shouldBeEqualToString("postedMimeType",
                                    testCase.expectedMime);
          }
      } else if (xhr.status === 0 && testCase.shouldThrow){
          testPassed("Cross-origin request without CORS headers should fail.");
      } else {
          testFailed("Unknown error");
      }

      runNextAsyncTest();
  }

  function runAsyncTests() {
      if (asyncTestCase >= xhrBlobTestCases.length) {
          finishJSTest();
          return;
      } else {
          var testCase = xhrBlobTestCases[asyncTestCase];
          var mime = testCase.mime;
          var file = testCase.file;
          var url = testCase.url !== undefined ? testCase.url + xhrBlobTestUrl : xhrBlobTestUrl;
          url += testCase.allowOrigin || "";
          if (testCase.shouldThrow !== undefined) {
              try {
                  testBlobContentTypeAsync(url, mime, file, testCase.closeBeforeSend);
              } catch (e) {
                  testPassed("Exception should be thrown.")
                  runNextAsyncTest();
              }
          } else
              testBlobContentTypeAsync(url, mime);
      }
  }

  function testBlobContentTypeAsync(url, mimeType, fileName, closeBeforeSend) {
      var blob;
      if (fileName) {
          if (mimeType !== "")
              blob = new File(["Test content"], fileName, {type: mimeType});
          else
              blob = new File(["Test content"], fileName);
      } else {
          if (mimeType !== "")
              blob = new Blob(["Test content"], {type: mimeType});
          else
              blob = new Blob(["Test content"]);
      }

      xhr = new XMLHttpRequest();
      xhr.onloadend = reportResult;
      xhr.open("POST", url, true);
      if (closeBeforeSend)
          blob.close();
      xhr.send(blob);
  }

  runAsyncTests();

</script>
